<template>
  <div v-if="valueType">
    <TypeSelect v-model="varlike.type" :explicit="true" mb2/>
    <VarInput v-model:varlike="varlike"/>
  </div>
</template>

<script setup lang="ts">
import type { WritableComputedRef } from 'vue';
import { VarInit } from "~/models/data/var_init";
import { TypesInherent } from '~/models/types';
import type { DataType } from '~/models/types/type';
import { getTypesFromModules } from '~/models/types/utils';

const props = defineProps<{
  modelValue: any
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', event: any): void,
}>()


const typesFromModules = getTypesFromModules()
const allTypes = [
  ...TypesInherent,
  ...typesFromModules
].filter(t => {
  return !t.name.includes('any') && !t.name.includes('|')
})

const valueType = ref(null as DataType | null)

watch(() => props.modelValue, val => {
  for (const paraType of allTypes) {
    if (paraType.receiveValue(props.modelValue)) {
      valueType.value = paraType
    }
  }
}, { immediate: true })


const varlike: WritableComputedRef<VarInit, VarInit> = computed({
  get(): VarInit {
    return new VarInit('', valueType.value!, props.modelValue)
  },
  set(gvar) {
    emit('update:modelValue', gvar.initial)
    valueType.value = gvar.type
  }
})
</script>

<style lang="scss">
.var-input-choice {
  width: 120px;
  background: #fff;
  border-radius: 4px;
  overflow: hidden;
  outline: none;
  .el-select__wrapper {
    color: #000;
  }
  .el-select__selected-item.el-select__placeholder {
    color: #000;
  }
}
</style>